/**
 * http请求方式: POST https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=ACCESS_TOKEN
 */
package com.viewhigh.wechat.sdk.api;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.sword.lang.HttpUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.viewhigh.framework.common.log.LogUtils;
import com.viewhigh.wechat.sdk.base.BaseApi;
import com.viewhigh.wechat.sdk.event.MsgType;
import com.viewhigh.wechat.sdk.response.ArticleResponse;
import com.viewhigh.wechat.sdk.response.MusicResponse;
import com.viewhigh.wechat.sdk.response.VideoResponse;

/**
 * 
 * @ClassName: CustomerMsg
 * @Description: 发送客服消息
 * @author liusongqing
 * @date 2016年9月23日 下午11:04:14
 *
 */
public class CustomerMsgApi extends BaseApi{
    private static final String MSG_URL = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=";

    //private static String toUserOpenId;
    private static String msgType; // msgtype
    private static String msgBody; // 发送的消息post数据
    //private static String appId;

    /**
     * 需要主动去刷新access_token,不建议使用 建议自己去获取access_token保存，并定时刷新。 然后使用SendMsg(String toUserOpenId,String accessToken)来替代本方法
     * 
     * @param toUserOpenId
     */
    /*public CustomerMsgApi(String toUserOpenId,String appId) {
        CustomerMsgApi.toUserOpenId = toUserOpenId;
        CustomerMsgApi.appId = appId;
    }*/

    //
    // public String getMsgBody() {
    // return msgBody;
    // }

    /**
     * 发送客服消息
     * 
     * @param msgBody
     */
    private static String send(String toUserOpenId,String appId) {
        if (StringUtils.isBlank(toUserOpenId)){
            LogUtils.error("发送客服失败，无法得到toUserOpenId");
            return "-1";
        }
        // token不存在则重新刷新token
        if (StringUtils.isBlank(getAccessTokenStr(appId))) {
            LogUtils.error("发送客服失败，无法得到accessToken");
            return "-1";
        }
        // 需要判断一下，防止上面刷新token失败
        String result = "-1";
        if (StringUtils.isNotBlank(getAccessTokenStr(appId))) {
            String url = MSG_URL + getAccessTokenStr(appId);
            String resultStr = HttpUtils.post(url, msgBody);
            // 发送失败 重新返回队列重试，直到成功为止
            if(StringUtils.isBlank(resultStr)){
                LogUtils.error("HttpUtils.post：发送客服消息失败，返回值为null，进行重试");
                for(int i=0;i<4;i++){
                    LogUtils.error("HttpUtils.post：发送客服消息 重试第："+i+1+"次。。。");
                    resultStr = HttpUtils.post(url, msgBody);
                    if(StringUtils.isNotBlank(resultStr)){
                        // 解析请求数据
                        JSONObject resultJson = JSONObject.parseObject(resultStr);
                        LogUtils.error("解析resultJson成功:"+resultStr);
                        if (resultJson != null) {
                            if (org.apache.commons.lang.StringUtils.isNotBlank(resultJson.getString("errcode"))) {
                                if (resultJson.getString("errcode").equals("0")) {
                                    LogUtils.error("HttpUtils.post：发送客服消息 重试第："+i+1+"次成功");
                                    result = "0";
                                } else {
                                    LogUtils.error("客服消息发送失败"+resultStr );
                                    result = "-1";
                                }
                            }
                        }
                        break;
                    }else{
                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                            LogUtils.error("HttpUtils.post：发送客服消息,线程暂停失败，msg:"+e.getMessage());
                        }
                    }
                }
            }else{
                // 解析请求数据
                JSONObject resultJson = JSONObject.parseObject(resultStr);
                LogUtils.error("解析resultJson成功:"+resultStr);
                if (resultJson != null) {
                    if (org.apache.commons.lang.StringUtils.isNotBlank(resultJson.getString("errcode"))) {
                        if (resultJson.getString("errcode").equals("0")) {
                            LogUtils.error("客服消息发送成功" );
                            result = "0";
                        } else {
                            LogUtils.error("客服消息发送失败"+resultStr );
                            result = "-1";
                        }
                    }
                }
            }
        }
        return result;
    }

    /**
     * { "touser":"OPENID", "msgtype":"text", "text": { "content":"Hello World" } }
     * 
     * @param content
     */
    public static String sendText(String content,String toUserOpenId,String appId) {
        msgType = MsgType.text.name();

        JSONObject jsonMsg = new JSONObject();
        jsonMsg.put("content", content);

        JSONObject json = new JSONObject();
        json.put("touser", toUserOpenId);
        json.put("msgtype", msgType);
        json.put("text", jsonMsg);

        msgBody = json.toJSONString();
        return send(toUserOpenId,appId);
    }

    /**
     * 发送图片消息 { "touser":"OPENID", "msgtype":"image", "image": { "media_id":"MEDIA_ID" } }
     * 
     * @param mediaId
     */
    public static String sendImage(String mediaId,String content,String toUserOpenId,String appId) {
        msgType = MsgType.image.name();

        JSONObject jsonMsg = new JSONObject();
        jsonMsg.put("media_id", mediaId);

        JSONObject json = new JSONObject();
        json.put("touser", toUserOpenId);
        json.put("msgtype", msgType);
        json.put("image", jsonMsg);

        msgBody = json.toJSONString();

        return send(toUserOpenId,appId);
    }

    /**
     * 发送语音消息
     * 
     * { "touser":"OPENID", "msgtype":"voice", "voice": { "media_id":"MEDIA_ID" } }
     */
    public static String sendVoice(String mediaId,String toUserOpenId,String appId) {
        msgType = MsgType.voice.name();

        JSONObject jsonMsg = new JSONObject();
        jsonMsg.put("media_id", mediaId);

        JSONObject json = new JSONObject();
        json.put("touser", toUserOpenId);
        json.put("msgtype", msgType);
        json.put("voice", jsonMsg);

        msgBody = json.toJSONString();
        return send(toUserOpenId,appId);
    }

    /**
     * 发送视频消息
     * 
     * 
     * @param title
     * @param description
     * @param mediaId
     * @param thumbMediaId
     */
    public static void sendVideo(String title, String description, String mediaId, String thumbMediaId,String toUserOpenId,String appId) {
        VideoResponse video = new VideoResponse();
        video.setTitle(title);
        video.setDescription(description);
        video.setMediaId(thumbMediaId);
        video.setThumbMediaId(thumbMediaId);
        sendVideo(video,toUserOpenId,appId);
    }

    /**
     * 发送视频消息 { "touser":"OPENID", "msgtype":"video", "video": { "media_id":"MEDIA_ID", "thumb_media_id":"MEDIA_ID",
     * "title":"TITLE", "description":"DESCRIPTION" } }
     * 
     * @param video
     */
    public static String sendVideo(VideoResponse video,String toUserOpenId,String appId) {
        msgType = MsgType.video.name();

        JSONObject jsonMsg = new JSONObject();
        jsonMsg.put("media_id", video.getMediaId());
        jsonMsg.put("thumb_media_id", video.getThumbMediaId());
        jsonMsg.put("title", video.getTitle());
        jsonMsg.put("description", video.getDescription());

        JSONObject json = new JSONObject();
        json.put("touser", toUserOpenId);
        json.put("msgtype", msgType);
        json.put("video", jsonMsg);

        msgBody = json.toJSONString();
        return send(toUserOpenId,appId);
    }

    /**
     * 发送音乐消息
     * 
     * @param title
     * @param description
     * @param musicURL
     * @param hQMusicUrl
     * @param thumbMediaId
     */
    public static String sendMusic(String title, String description, String musicURL, String hQMusicUrl,
            String thumbMediaId,String toUserOpenId,String appId) {
        MusicResponse music = new MusicResponse();
        music.setTitle(title);
        music.setDescription(description);
        music.setMusicURL(musicURL);
        music.setHQMusicUrl(hQMusicUrl);
        music.setThumbMediaId(thumbMediaId);
        return sendMusic(music,toUserOpenId,appId);
    }

    /**
     * 发送音乐消息 { "touser":"OPENID", "msgtype":"music", "music": { "title":"MUSIC_TITLE",
     * "description":"MUSIC_DESCRIPTION", "musicurl":"MUSIC_URL", "hqmusicurl":"HQ_MUSIC_URL",
     * "thumb_media_id":"THUMB_MEDIA_ID" } }
     * 
     * @param music 音乐消息
     */
    public static String sendMusic(MusicResponse music,String toUserOpenId,String appId) {
        msgType = MsgType.music.name();

        JSONObject jsonMsg = new JSONObject();
        jsonMsg.put("title", music.getTitle());
        jsonMsg.put("description", music.getDescription());
        jsonMsg.put("musicurl", music.getMusicURL());
        jsonMsg.put("hqmusicurl", music.getHQMusicUrl());
        jsonMsg.put("thumb_media_id", music.getThumbMediaId());

        JSONObject json = new JSONObject();
        json.put("touser", toUserOpenId);
        json.put("msgtype", msgType);
        json.put("music", jsonMsg);

        msgBody = json.toJSONString();
        return send(toUserOpenId,appId);
    }

    /**
     * 发送图文消息，单条图文消息
     * 
     * @param Title 图文消息标题
     * @param Description 图文消息描述
     * @param PicUrl 图片链接，支持JPG、PNG格式，较好的效果为大图360*200，小图200*200
     * @param Url 点击图文消息跳转链接
     */
    public static String sendNew(String title, String description, String picUrl, String url,String toUserOpenId,String appId) {
        ArticleResponse item = new ArticleResponse();
        item.setTitle(title);
        item.setDescription(description);
        item.setPicUrl(picUrl);
        item.setUrl(url);
        return sendNews(item,toUserOpenId,appId);
    }

    /**
     * 发送图文消息，单条图文消息
     * 
     * @param item
     */
    public static String sendNews(ArticleResponse item,String toUserOpenId,String appId) {
        List<ArticleResponse> items = new ArrayList<ArticleResponse>();
        items.add(item);
        return sendNews(items,toUserOpenId,appId);
    }

    /**
     * 发送图文消息 { "touser":"OPENID", "msgtype":"news", "news":{ "articles": [ { "title":"Happy Day", "description":
     * "Is Really A Happy Day", "url":"URL", "picurl":"PIC_URL" }, { "title":"Happy Day", "description":
     * "Is Really A Happy Day", "url":"URL", "picurl":"PIC_URL" } ] } }
     * 
     * @param items
     */
    public static String sendNews(List<ArticleResponse> items,String toUserOpenId,String appId) {
        msgType = MsgType.news.name();
        JSONArray jsonArray = new JSONArray();
        for (ArticleResponse item : items) {
            JSONObject jsonItem = new JSONObject();
            jsonItem.put("title", item.getTitle());
            jsonItem.put("description", item.getDescription());
            jsonItem.put("url", item.getUrl());
            jsonItem.put("picurl", item.getPicUrl());

            jsonArray.add(jsonItem);
        }

        JSONObject jsonMsg = new JSONObject();
        jsonMsg.put("articles", jsonArray);

        JSONObject json = new JSONObject();
        json.put("touser", toUserOpenId);
        json.put("msgtype", msgType);
        json.put("news", jsonMsg);

        msgBody = json.toJSONString();
        return send(toUserOpenId,appId);
    }
}
